// 初始化页面数据
// 查看账单的类型 0-待确认 1-贷结款 2-已结款 3-有问题
var queryBillStatus = 9;
var queryStatusArray = ["待确认", "已确认", "已结款", "有问题"];
$(function () {
    $("#endTime").my97({
        prompt: '开始时间',
        dateFmt: 'yyyy-MM-dd'
    });
    $("#beginTime").my97({
        prompt: '开始时间',
        dateFmt: 'yyyy-MM-dd'
    });
    initDatagrid();
    // 账单状态，全局
    $("#Status").combobox({
        onSelect: function (res) {
            queryBillStatus = res.value;
        }
    });
    // 商品查询
    $("#queryButton").click(function () {
        var beginTime = $('#beginTime').datetimebox('getValue');
        var endTime = $('#endTime').datetimebox('getValue');
        if (beginTime != "" && endTime == "") {
            $.messager.alert('提示', '未选择结束时间', 'info');
            return;
        }
        if (beginTime == "" && endTime != "") {
            $.messager.alert('提示', '未选择开始时间', 'info');
            return;
        }
        if (beginTime != "" && endTime != "") {
            $("#listTable").datagrid('load', {
                queryStr: $("#queryStr").val(),
                beginTime: beginTime,
                endTime: endTime,
                status: queryBillStatus
            })
        } else {
            $("#listTable").datagrid('load', {
                queryStr: $("#queryStr").val(),
                status: queryBillStatus
            })
        }

    })
});

// 表格内容初始化
function initDatagrid() {
    var url = $.util.getRequestJson('/json/consumeManage.billList.json');
    $('#listTable').datagrid({
        url: url /*+ '?type=0'*/,
        idField: 'id',
        queryParams: {
            status: queryBillStatus
        },
        fit: true,
        pagination: true,
        pageSize: 30,
        rownumbers: true,
        checkOnSelect: false,
        selectOnCheck: false,
        singleSelect: true,
        toolbar: '#toolbarButton',
        fitColumns: true,
        columns: [
            [
                {
                    field: 'storeName',
                    title: '商户名称',
                    width: 20,
                    formatter: function (value, row, index) {
                        return value == null ? "——" : value;
                    }
                },
                {
                    field: 'finishTime',
                    title: '结算时间',
                    align: 'center',
                    width: 15
                },
                {
                    field: 'temp',
                    title: '账单周期',
                    align: 'center',
                    width: 20,
                    formatter: function (value, row, index) {
                        return "[" + row.beginTime + "]-[" + row.endTime + "]";
                    }
                },
                {
                    field: 'sumScore',
                    title: '待结算积分',
                    align: 'center',
                    width: 10
                }, /*{
                    field: 'payMoney',
                    title: '待结算金额',
                    align: 'center',
                    width:12
                },*/{
                field: 'status',
                title: '状态',
                align: 'center',
                width: 10,
                formatter: function (value, row) {
                    return queryStatusArray[value];
                }
            }, {
                field: 'paymentTime',
                title: '结款时间',
                align: 'center',
                width: 15,
                formatter: function (value, row) {
                    return value == null ? "--" : value;
                }
            }, {
                field: 'context',
                width: 20,
                title: '操作',
                align: 'center',
                formatter: function (value, row, index) {
                    var aEl = '<a href=javascript:findDetail("{0}","{1}","{2}"); class="easyui-tooltip" title="详情">详情</a>';
                    if (row.status == 1) {
                        // 有问题的账单需要调整
                        aEl = '<a href=javascript:findDetail("{0}","{1}","{2}"); class="easyui-tooltip" title="详情&结款">详情&结款</a>';
                    }
                    //格式化操作按钮
                    return $.string.format(aEl, index, row.id, row.storeId);
                }
            }
            ]
        ]
    });
}

// 新建查询账单
function buildNewBill() {
    var title = "新建对账单";
    var url = $.util.getRootPath() + '/page/operatorManager/billManager/buildNewBill.html';
    //url = id ? url + '?id=2&typeId=' + typeId : url;
    var dialog = $.easyui.showDialog({
        iconCls: "",
        title: title,
        width: 400,
        height: 500,
        maximizable: true,
        href: url,
        topMost: true,
        saveButtonText: '生成账单',
        onSave: function () {
            buildBillOpt(dialog);
        }
    });
}

// 查看账单详情
function findDetail(index, billId, storeId) {
    var buttons;
    if ($("#listTable").datagrid('getRows')[index].status == 1) {
        buttons = [
            {
                iconCls: 'icon-check',
                text: '结款',
                handler: function () {
                    payOffOpt(index, dialog);
                }
            }
        ];
    } else {
        buttons = [];
    }
    var title = "账单详情";
    var url = $.util.getRootPath() + '/page/operatorManager/billManager/billDetail.html?storeId=' + storeId + "&billId=" + billId;
    var dialog = $.easyui.showDialog({
        iconCls: "",
        title: title,
        width: 1000,
        height: 600,
        maximizable: true,
        href: url,
        topMost: true,
        enableSaveButton: false,
        closeButtonText: '关闭',
        onSave: function () {
            reviseBillOpt(dialog);
        },
        buttons: buttons
    });
}

// 调整问题账单
function reviseBill(billId) {
    var title = "调整账单";
    var url = $.util.getRootPath() + '/page/operatorManager/billManager/reviseBill.html?id=' + billId;
    var dialog = $.easyui.showDialog({
        iconCls: "",
        title: title,
        width: 800,
        height: 500,
        maximizable: true,
        href: url,
        topMost: true,
        saveButtonText: '保存',
        onSave: function () {
            reviseBillOpt(dialog);
        }
    });
}

// 调整账单操作
function reviseBillOpt() {
    var url = $.util.getRootPath() + '/consumeManage/reviseBill';
    var form = parent.$('#reviseBill').form('submit', {
        url: url,
        onSubmit: function () {
            return parent.$('#reviseBill').form('validate');
        },
        success: function (data) {
            if (data.success) {
                $('#listTable').datagrid('reload');
                dialog.dialog('close');
            }
            $.easyui.messager.show(data.message);
        }
    });
}

// 创建新账单，上传保存
function buildBillOpt(dialog) {
    var beginTime = parent.$('#beginTime_').datetimebox('getValue');
    var endTime = parent.$('#endTime_').datetimebox('getValue');
    if (beginTime == "") {
        parent.$.messager.alert('提示', '未选择开始时间', 'info');
        return;
    }
    if (endTime == "") {
        parent.$.messager.alert('提示', '未选择结束时间', 'info');
        return;
    }
    if (beginTime > endTime) {
        parent.$.messager.alert('提示', '结束时间不能早于结束时间', 'info');
        return;
    } else {
        // 进行新建账单操作 提交操作
        var url = $.util.getRootPath() + '/consumeManage/saveBill';
        var form = parent.$('#buildNewBill').form('submit', {
            url: url,
            onSubmit: function () {
                return parent.$('#buildNewBill').form('validate');
            },
            success: function (data) {
                if (data.success) {
                    $('#listTable').datagrid('reload');
                    dialog.dialog('close');
                }
                $.easyui.messager.show(data.message);
            }
        });
    }
}

// 结款操作
function payOffOpt(index, dialog) {
    var row = $("#listTable").datagrid('getRows')[index];
    var date = new Date();
    var time = date.getFullYear() + "年" + (date.getMonth() + 1) + "月" + date.getDate() + "日";
    var confirmStr = "确定给" + row.storeName + "结款?" + /*row.payMoney+"元+*/"<br/>付款日期：" + time + "<br/>";
    parent.$.messager.confirm('确定付款？', confirmStr, function (r) {
        if (r) {
            $.util.get($.util.getRequestJson('/json/consumeManage.settleBill.json'), {
                billId: row.id,
                status: 2
            }, function (data) {
                $('#listTable').datagrid('reload');
                dialog.dialog('close');
            });
        }
    });
}

// 导出所有数据
function exportBillList() {
    $.util.get($.util.getRequestJson('/json/consumeManage.exportBillList.json'), {
        queryStr: $("#queryStr").val(),
        beginTime:  $('#beginTime').datetimebox('getValue'),
        endTime: $('#endTime').datetimebox('getValue'),
        status: queryBillStatus
    }, function (data) {
        var $a = $("<a></a>").attr("href", data.data).attr("download", "data.xlsx");
        $a[0].click();
    });
}